package net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders.condition;

import java.util.HashMap;
import java.util.Map;

import net.valerijtimakov.homefinances.domain.common.CheckedData;
import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;

public class WhereBuilder extends CheckedData {
	private String whereCond = "";
	private Map<String, ListCondBuilder<?>> listConditions = new HashMap<String, ListCondBuilder<?>>();
	private Map<String, IntervalConditionBuilder<?>> intervalCondtitions = new HashMap<String, IntervalConditionBuilder<?>>();
	
	public WhereBuilder() {
		super();
	}

	public String getWhereCond() {
		return whereCond;
	}

	public void setWhereCond(String whereCond) {
		this.whereCond = checkNull(whereCond);
	}
	
	public <TT> ListCondBuilder<TT> createListCondBuilder(String fieldName, Class<TT> classType) {
		ListCondBuilder<TT> res = new ListCondBuilder<TT>(fieldName);
		listConditions.put(fieldName, res);
		return res;
	}
	
	public <T> void addIntervalCondBuilder(String fieldName, T fromValue, T toValue) {
		addIntervalCondBuilder(fieldName, fromValue, toValue, false, false);
	}
	
	public <T> void addIntervalCondBuilder(String fieldName, T fromValue, T toValue, boolean strictFrom, boolean strictTo) {
		IntervalConditionBuilder<T> tmpIntervBuilder = new IntervalConditionBuilder<T>(fieldName);
		tmpIntervBuilder.setFromValue(fromValue);
		tmpIntervBuilder.setFromStrict(strictFrom);
		tmpIntervBuilder.setToStrict(strictTo);
		tmpIntervBuilder.setToValue(toValue);
		intervalCondtitions.put(fieldName, tmpIntervBuilder);
	}
	
	public StringBuilder getWhereConditionLine() throws AppExceptionWrongState {
		StringBuilder whereCondFull = new StringBuilder();
		for (ListCondBuilder<?> listCB : listConditions.values()) {
			listCB.addCondition(whereCondFull);
		}
		for (IntervalConditionBuilder<?> intervalCB : intervalCondtitions.values()) {
			intervalCB.addCondition(whereCondFull);
		}
		if (whereCondFull.length() > 0) {
			whereCondFull.insert(0, " WHERE ");
		}
		if (!whereCond.isEmpty()) {
			if (whereCondFull.length() > 0) {
				whereCondFull.append(" AND ");	
				whereCondFull.append(whereCond);
			} else {
				whereCondFull.append(" WHERE ");	
				whereCondFull.append(whereCond);
			}
		}
		return whereCondFull;
	}
}
